<body onload="get_todo_list()">
    <div>
        <h1>待办事项清单</h1>
        <input type="text" id="create" placeholder="添加待办事项">
        <input type="button" value="+" onclick="add()">


        <ul id="todolist"></ul>
    </div>
</body>


<script>

    function get_todo_list() {
        fetch("/todos")
            .then(res => res.json())
            .then(function (data) {
                var ele_list = document.getElementById("todolist");
                ele_list.innerHTML = "";
                var list = data.todos

                for (var i = 0; i < list.length; i++) {
                    if (!list[i].completed) {
                        var li = '<li> <input type="checkbox"  name="' + list[i].id + '" onchange="isFinish(this.name)">' + list[i].id + "、<span>" + list[i].title + '</span></li>';
                        document.getElementById("todolist").innerHTML += li;
                    }

                }
            }
            )
    }


    function add() {
        var title = document.getElementById('create').value;

        var url = "/todos";
        var headers = {
            "Content-Type": "application/x-www-form-urlencoded"
        }

        fetch(url, {
            method: 'POST',
            body: 'title=' + title,
            headers: headers
        })
            .then(
                res => res.json()
            )
            .then(function (data) {
                console.log(data)
                get_todo_list()

            }
            )
    }

    function isFinish(id) {
        fetch('/todos/mark_completed' + '?todo_id=' + id)
            .then(response => response.json())
            .then(function (x) {
                if ('title' in x) {
                    get_todo_list()
                }
            })
    }


</script>